#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

#include "nweb.h"
#include "nweb_log.h"
#include "http_dynamic_response.h"

/* Resource Handler */
void handle_dynamic_resource(request_rec* r, int file_fd) {
    long ret;

    FILE *fp;
    char line[256];
    char *application = getApplication(r);
    char command[strlen(application) + strlen(&r->uri[1])];
    strcat(command, application);
    strcat(command, &r->uri[1]);

    fp = popen(command, "r");

    while (fgets( line, sizeof line, fp))
    {
    	//printf("%s", line);
    	(void)write(r->fd, line, strlen(line));
    }

    pclose(fp);
}

char *getApplication(request_rec* r) {
	if(str_ends_with(r->uri, ".py")) {
		return "python ";
	}

	return "php ";
}

int str_ends_with(const char * str, const char * suffix) {

	if (str == NULL || suffix == NULL)
		return 0;

	size_t str_len = strlen(str);
	size_t suffix_len = strlen(suffix);

	if (suffix_len > str_len)
		return 0;

	return 0 == strncmp(str + str_len - suffix_len, suffix, suffix_len);
}
